<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警示框 -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      <!-- 步骤条 -->
      <el-steps :space="200" :active="parseInt(stepActive)" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 表单和tab栏 -->
      <el-form
        :model="addGoodForm"
        :rules="addGoodFormRules"
        ref="addGoodFormRef"
        label-position="top"
      >
        <el-tabs
          :tab-position="'left'"
          v-model="stepActive"
          :before-leave="beforeTabLeave"
          @tab-click="tabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addGoodForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight" type="number">
              <el-input v-model="addGoodForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number" type="number">
              <el-input v-model="addGoodForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addGoodForm.goods_cat"
                :options="cateList"
                :props="cascaderProps"
                @change="cascaderChange"
                clearable
                @clear="cascaderClear"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="cb" v-for="(cb, i) in item.attr_vals" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="action"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :headers="headers"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addGoodForm.goods_introduce" />
            <el-button type="primary" @click="addGoods" class="addGoodBtn">添加商品</el-button>
          </el-tab-pane>
          <el-tab-pane label="完成" name="5">完成</el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览窗口 -->
    <el-dialog title="图片预览" :visible.sync="previewDialogShow" width="50%">
      <img width="100%" :src="previewUrl" alt />
    </el-dialog>
  </div>
</template>

<script>
import * as allGoodsFunc from '@/network/goods'
import _ from 'lodash'
export default {
  name: 'Add',
  data() {
    return {
      // 步骤条默认值
      stepActive: '0',
      // 添加表单数据
      addGoodForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      // 添加商品表单的验证规则
      addGoodFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请输入商品分类', trigger: 'blur' }
        ]
      },
      // 商品分类数据
      cateList: [],
      // 级联选择器匹配规则
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover',
        checkStrictly: false
      },
      // 商品参数
      manyTableData: [],
      // 商品属性
      onlyTableData: [],
      // 图片预览框显示与否
      previewDialogShow: false,
      // 预览图片的url
      previewUrl: '',
      // 上传图片请求头设置
      headers: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 图片上传url
      action: 'http://127.0.0.1:8888/api/private/v1/upload'
    }
  },
  computed: {
    cateId() {
      if (this.addGoodForm.goods_cat.length === 3) {
        return this.addGoodForm.goods_cat[2]
      }
      return null
    }
  },
  created() {
    this.getCateData()
  },
  methods: {
    // 获取分类数据
    async getCateData() {
      const { data, meta } = await allGoodsFunc.allCateList()
      if (meta.status !== 200) {
        return this.$message.error(meta.msg)
      }
      console.log(data)
      this.cateList = data
      this.$message.success(meta.msg)
    },
    // 级联选择器发生改变
    cascaderChange() {
      if (this.addGoodForm.goods_cat.length !== 3) {
        this.addGoodForm.goods_cat = []
      }
    },
    // 级联选择器清空
    cascaderClear() {},
    // 标签页的切换
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addGoodForm.goods_cat.length !== 3) {
        this.$message.error('请选择商品分类')
        return false
      }
    },
    // 标签页被点击
    async tabClick() {
      if (this.stepActive === '1') {
        const { data, meta } = await allGoodsFunc.getAttributes(
          this.cateId,
          'many'
        )
        if (meta.status !== 200) {
          return this.$message.error(meta.msg)
        } else {
          data.forEach(item => {
            item.attr_vals =
              item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
          })
          this.manyTableData = data
        }
      } else if (this.stepActive === '2') {
        const { data, meta } = await allGoodsFunc.getAttributes(
          this.cateId,
          'only'
        )
        if (meta.status !== 200) {
          return this.$message.error(meta.msg)
        } else {
          this.onlyTableData = data
          console.log(this.onlyTableData)
        }
      }
    },
    // 图片预览
    handlePictureCardPreview(file) {
      this.previewUrl = file.response.data.url
      this.previewDialogShow = true
    },
    // 图片删除
    handleRemove(file) {
      const index = this.addGoodForm.pics.findIndex(
        item => item.pic === file.response.data.tmp_path
      )
      this.addGoodForm.pics.splice(index, 1)
    },
    // 图片上传成功
    handleSuccess(response) {
      const pic = { pic: response.data.tmp_path }
      this.addGoodForm.pics.push(pic)
    },
    // 添加商品
    async addGoods() {
      console.log(this.addGoodForm.goods_introduce)
      // 验证表单数据
      this.$refs.addGoodFormRef.validate(valid => {
        if (!valid) {
          return this.$message.error('请正确填写表单数据')
        }
      })
      // 处理表单提交数据
      const form = _.cloneDeep(this.addGoodForm)
      form.goods_cat = form.goods_cat.join(',')
      // attrs属性的处理
      // 动态参数
      this.manyTableData.forEach(item => {
        const obj = {
          attr_id: item.attr_id,
          attr_value: item.attr_vals.join(' ')
        }
        this.addGoodForm.attrs.push(obj)
      })
      // 静态参数
      this.onlyTableData.forEach(item => {
        const obj = {
          attr_id: item.attr_id,
          attr_value: item.attr_vals
        }
        this.addGoodForm.attrs.push(obj)
      })
      form.attrs = this.addGoodForm.attrs
      // 发送请求
      const { meta } = await allGoodsFunc.addGood(form)
      if (meta.status !== 201) {
        return this.$message.error(meta.msg)
      } else {
        this.$message.success(meta.msg)
        this.stepActive = '5'
        this.$router.push('/goods')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-card {
  height: 1000px;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.addGoodBtn{
  margin-top: 15px;
}
</style>
